/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.fr.demo.demos.web;

import com.fr.demo.model.Book;
import com.fr.demo.service.BookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author furen
 */
@Controller
public class BookController {

private static final Logger logger = LoggerFactory.getLogger(BookController.class);

    @Autowired
    private BookService bookService;

    @RequestMapping("/selectBook")
    @ResponseBody
    @Secured({"USER"})
    public String selectBook(@RequestParam(name = "id", defaultValue = "0") Long id) {
        Book book = bookService.getBookById(id);
        logger.info("查询出来的数据{}",book);
        if(book == null){
            return "selectBook1 " + "no book";
        }else{
            return "selectBook " + book.getName();
        }
    }

    @RequestMapping("/selectAllBook")
    @ResponseBody
    //@Secured({"ADMIN"})
    @PreAuthorize("hasRole('ADMIN')")
    public List<Book> selectAllBook() {
        List<Book> books = bookService.selectAllBook();
        logger.info("1查询出来的数据所有书籍{}",books);
        return books;
    }

    @RequestMapping("/addBook")
    @ResponseBody
    public String addBook(@RequestParam(name = "name", defaultValue = "unknown book") String name) {
        Book book = new Book();
        book.setName("python编程");
        bookService.addBook(book);
        return "addBook1 " + name;
    }

    @RequestMapping("/updateBook")
    @ResponseBody
    public String updateBook(@RequestParam(name = "name", defaultValue = "unknown book") String name,@RequestParam(name = "id") Long id) {
        bookService.updateBook(id,name);
        return "updateBook " + name;
    }

    @RequestMapping("/deleteBook")
    @ResponseBody
    public String deleteBook(@RequestParam(name = "id") Long id) {
        bookService.deleteBook(id);
        return "deleteBook " + id;
    }

}
